package killerqueen.game.objects;

import killerqueen.game.interfaces.GameObject;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;
import org.jbox2d.dynamics.World;
import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.geom.Polygon;

public class Platform implements GameObject {

	private float w;
	private float h;
	private float x;
	private float y;

  private PolygonShape box;
  private Body body;
  private Vec2 speed = new Vec2(0, 3);
  private float maxHeight = 10;
  private float minHeight = 2;

  public Platform() {
  }


  @Override
  public void init(World world, String id) {
    BodyDef bodyDef = new BodyDef();

    bodyDef.position.set(x, y);
    bodyDef.type = BodyType.KINEMATIC;
    body = world.createBody(bodyDef);


    box = new PolygonShape();
    box.setAsBox( w, h);

    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = box;
    fixtureDef.density = 5;
    fixtureDef.friction = 1f;
    fixtureDef.restitution = 0.1f;

    body.createFixture(fixtureDef);
    body.setLinearVelocity(speed);
  }

  @Override
  public void input(Input input) {
    // TODO Auto-generated method stub
  }

  @Override
  public void paint(Graphics g) {
    g.pushTransform();

    Polygon p = new Polygon();

    Vec2 pos = body.getPosition();
    float angle = body.getAngle();
    g.translate(pos.x, pos.y);
    g.rotate(0, 0, (float) Math.toDegrees(+angle));

    for (int i = 0; i < box.getVertexCount(); i++) {
      Vec2 vertex = box.getVertex(i);
      p.addPoint(vertex.x, vertex.y);
    }

    g.setColor(Color.blue);
    g.fill(p);
    g.setColor(Color.black);
    g.draw(p);

    g.popTransform();

  }

  @Override
  public void update(long delta) {
    if (body.getPosition().y > maxHeight && body.getLinearVelocity().y > 0) {
      if (body.getLinearVelocity().y > 0.3)
        body.setLinearVelocity(new Vec2(0f, body.getLinearVelocity().y * 0.9f));
      else
        body.setLinearVelocity(new Vec2(0f, -0.3f));
      return;
    }

    if (body.getPosition().y > maxHeight && body.getLinearVelocity().y < 0) {
      body.setLinearVelocity(new Vec2(0f, body.getLinearVelocity().y * 1.1f));
      return;
    }

    if (body.getPosition().y < minHeight) {
      body.setLinearVelocity(new Vec2(0, speed.y));
      return;
    }
  }
  
  public void setW(float w) {
		this.w = w;
	}

	public void setH(float h) {
		this.h = h;
	}

	public void setX(float x) {
		this.x = x;
	}

	public void setY(float y) {
		this.y = y;
	}


	@Override
	public void destroy(World world) {
		// TODO Auto-generated method stub
		
	}

}
